package com.ithuang.quartz.task;

import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;

import java.awt.*;
import java.awt.image.BufferedImage;

public class Xxxxxxx {
    
    
    //1将彩色图像转换为灰度图像，可以减少噪声和提高OCR的准确性。使用Java的BufferedImage类可以轻松实现这一点。
    public BufferedImage convertToGrayscale(BufferedImage image) {
        BufferedImage grayscaleImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
        Graphics2D g = grayscaleImage.createGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return grayscaleImage;
    }
    //2二值化是将图像转换为黑白图像。通过二值化，可以去除背景噪声，突出目标区域。
    public BufferedImage binarizeImage(BufferedImage image) {
        BufferedImage binaryImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
        Graphics2D g = binaryImage.createGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return binaryImage;
    }
    // 2. 图像ocr
    public String extractTextFromImage(BufferedImage image) {
        try {
            Tesseract tesseract = new Tesseract();
            return tesseract.doOCR(image);
        } catch (TesseractException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public String shibie(BufferedImage image) throws TesseractException{
        // 1. 初始化Tesseract OCR引擎
        Tesseract tesseract = new Tesseract();
        tesseract.setDatapath("E://"); // 设置tessdata路径
        tesseract.setLanguage("eng"); // 设置语言
        image = convertToGrayscale(image);
        image = binarizeImage(image);
        String s = tesseract.doOCR(image);
        return s;
    }

}
